package project2.ui.manage.operate;

import project2.entity.Score;
import project2.resources.Scores;
import project2.resources.Sounds;
import project2.ui.MainFrame;
import project2.ui.manage.HelpDialog;
import project2.ui.manage.Top10ScorePanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class MenuChoose implements ActionListener {
    private final MainFrame mainFrame;

    public MenuChoose(MainFrame mainFrame) {
        this.mainFrame = mainFrame;
    }

    /**
     * 监听触发各种行为
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if (source == mainFrame.popupMenuPanel.startGameButton) {// 开始新游戏
            startGameAction();
        } else if (source == mainFrame.popupMenuPanel.top10ScoresButton) {// 查看分数记录
            Sounds.achievementSoundPlayer.play();
            popupScorePanel(Scores.scoreList);
        } else if (source == mainFrame.popupMenuPanel.exitGameButton) {// 退出游戏
            System.exit(0);
        } else if (source == mainFrame.popupMenuPanel.helpButton) {// 帮助窗口
            helpAction();
        } else if (source == mainFrame.popupScorePanel.okButton) {// 分数记录面板返回到菜单面板
            mainFrame.popupMenuPanel();
        }
    }

    /**
     * 开始新游戏
     */
    private void startGameAction() {
        new Thread(() -> {// 因为开始游戏的时间很长，无法在监听器中快速完成，所以开启线程执行
            try {
                mainFrame.loadGame();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 打开分数记录面板
     */
    private void popupScorePanel(List<Score> sortedScoreList) {
        // 画布上有内容则清理掉
        Container c = mainFrame.getContentPane();
        c.removeAll();
        mainFrame.repaint();
        // 创建分数记录面板
        if (mainFrame.popupScorePanel == null) {
            mainFrame.popupScorePanel = new Top10ScorePanel(mainFrame);
        }
        mainFrame.popupScorePanel.loadScore(sortedScoreList);// 分数记录面板加载分数
        // 画布上放入面板
        c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
        c.add(Box.createVerticalGlue());
        c.add(mainFrame.popupScorePanel);
        c.add(Box.createVerticalGlue());
        mainFrame.validate();// 重新调整大小，前提是已经设置大小（已经调用了setSize()），且大小发生变化。
    }

    /**
     * 打开帮助窗口
     */
    private void helpAction() {
        if (mainFrame.helpDialog == null) {
            mainFrame.helpDialog = new HelpDialog();
        }
        mainFrame.helpDialog.setVisible(true);
    }
}
